package com.gcloud.image.driver;

import org.springframework.stereotype.Component;

import com.gcloud.common.util.StringUtils;
import com.gcloud.common.util.SystemUtil;
import com.gcloud.core.exception.GCloudException;
/**
 * 存放在rbd上的镜像缓存
 *
 */
@Component
public class ImageCacheRbdStoreDriverImpl implements IImageCacheStoreDriver {

	@Override
	public void deleteImageCache(String imageId, String storeTarget) {
		String[] snapLsCmd = new String[] {"rbd", "snap", "ls", "images/" + imageId};
    	if(StringUtils.isNotBlank(SystemUtil.run(snapLsCmd))) {
        	String[] snapUnProtectCmd = new String[] {"rbd", "snap", "unprotect", "images/" + imageId +"@snap"};
        	int unProtectRes = SystemUtil.runAndGetCode(snapUnProtectCmd);
        	if(unProtectRes != 0) {
            	throw new GCloudException("::images池镜像" + imageId + "快照解保护失败");
            }
        	
        	String[] snapDelCmd = new String[] {"rbd", "snap", "rm", "images/" + imageId +"@snap"};
        	int snapDelRes = SystemUtil.runAndGetCode(snapDelCmd);
        	if(snapDelRes != 0) {
            	throw new GCloudException("::images池镜像" + imageId + "快照删除失败");
            }
    	}
		
		//删掉images池上对应的image cache , rbd rm  -p images  imageId 
		String[] deleteCmd = new String[]{"rbd", "rm", "-p", storeTarget , imageId};
        int deleteRes = SystemUtil.runAndGetCode(deleteCmd);
        if(deleteRes != 0) {
        	throw new GCloudException("::删除images池上的镜像" + imageId + "失败");
        }
	}

}
